package fm.listener;

import fm.model.FileUploadStatus;
import fm.util.CommonUtils;
import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;

/**
 * 类名：fm.listener.FileUploadProgressListener
 * 创建者： CM .
 * 创建时间：2016/3/17
 */
@Component
public class FileUploadProgressListener implements ProgressListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadProgressListener.class);
    public static final String FILE_UP_LOAD_STATUS = "$_FILE_UP_LOAD_STATUS";
    @Autowired
    HttpSession session;


    /**
     * 更新文件上传进度
     *
     * @param readLength       到目前为止读取文件的比特数
     * @param fileLength       文件总大小
     * @param currentItemIndex 目前正在读取第几个文件
     */
    @Override
    public void update(long readLength, long fileLength, int currentItemIndex) {
        FileUploadStatus fus = (FileUploadStatus) session.getAttribute(FILE_UP_LOAD_STATUS);
        fus = CommonUtils.isEmpty(fus) ? new FileUploadStatus() : fus;
        fus.setCurrentItemIndex(currentItemIndex);
        fus.setFileLength(fileLength);
        fus.setReadLength(readLength);
        session.setAttribute(FILE_UP_LOAD_STATUS, fus);
//        LOGGER.debug("file upload progress:{}", new DecimalFormat("#.00").format((double) fus.getReadLength() * 100 / (double) fus.getFileLength()));
    }


}
